package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.config.LiveProperties;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAddUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

    @Autowired
    private LiveRoomMapper liveRoomMapper;
    @Resource
    private LiveProperties liveProperties;
    @Resource
    private LiveAddUtil liveAddUtil;

    @Override
    public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
        //判断当前用户是否存在未过期的直播间
        LiveRoom liveRoom = getOne(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId, AuthContextHolder.getUserId())
                .ge(LiveRoom::getCreateTime, new Date()));
        if (liveRoom != null) {
            return liveRoom;
        }
        //没有未过期的直播间，则新增直播间
        liveRoom = new LiveRoom();
        BeanUtils.copyProperties(liveRoomVo,liveRoom);
        liveRoom.setUserId(AuthContextHolder.getUserId());
        liveRoom.setStatus("0");
        liveRoom.setAppName(liveProperties.getAppName());
        liveRoom.setStreamName("glsx-"+ UUID.randomUUID());
        TencentLiveAddressVo addressUrl = liveAddUtil.getAddressUrl(liveRoom.getStreamName(),liveRoom.getExpireTime());
        liveRoom.setPushUrl(addressUrl.getPushWebRtcUrl());
        liveRoom.setPlayUrl(addressUrl.getPullWebRtcUrl());
        save(liveRoom);
        return liveRoom;
    }
}
